package com.mmp.main.servlet;

import java.io.IOException;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mmp.common.bo.Message;
import com.mmp.common.bo.Message.MESSAGE_TYPE;
import com.mmp.common.servlet.BasicServlet;
import com.mmp.main.DB.DBQueryManager;
import com.mmp.main.entity.JobOrder;
import com.mmp.main.util.Default;
import com.mmp.main.util.Enums;

public class SearchForJobOrderProcessServlet extends BasicServlet {

	private static HashMap<String, String> destinations;

	static {
		destinations = new HashMap<String, String>();
		destinations.put(Default.SEARCH_DEST_CANCEL_JOB_OREDR_PARAM_VALUE, "JobOrderDeleteDisplay");
		destinations.put(Default.SEARCH_DEST_FOLLOWUP_JOB_OREDR_PARAM_VALUE, "JobOrderTrackingDisplay");
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String orderNo = request.getParameter("jobOrderNo");
		String sn = request.getParameter("deviceSerial");
		String code = request.getParameter("deviceCode");

		// order.getHospitalDevice().getJobOrders().size();
		// Hibernate.initialize(order);

		JobOrder order = new DBQueryManager(dbm).getOpenedJobOrder(orderNo, code, sn, getDeviceStatus(request));

		if (order == null) {
			setMessage(request, new Message("لا توجد نتائج للبحث أو لا يوجد أمر عمل مفتوح بالبيانات الموافقة لبحثك",
					MESSAGE_TYPE.ERROR));
			basicForward(request, response, "SearchForJobOrderDisplay");
			return;
		}

		request.setAttribute(Default.JOB_ORDER_INFO_ATTR_NAME, order);
		request.setAttribute(Default.DEVICE_INFO_ATTR_NAME, order.getHospitalDevice());
		basicForward(request, response, getSearchDestination(destinations, request));
	}

	private Enums.DEVICE_STATUS getDeviceStatus(HttpServletRequest request) {

		String dest = request.getParameter(Default.SEARCH_DEST_PARAM_NAME);

		if (Default.SEARCH_DEST_CANCEL_JOB_OREDR_PARAM_VALUE.equals(dest)
				|| Default.SEARCH_DEST_FOLLOWUP_JOB_OREDR_PARAM_VALUE.equals(dest))
			return Enums.DEVICE_STATUS.UNDER_MAINTENANCE;

		return null;

	}

}
